<!DOCTYPE html>
<html>
	<body>
		<script src="common.js"></script>
		<script type="text/javascript">
			var options;

			// Converts a string to a boolean value
			function toBool(str) {
				return "false" === str ? false : true;
			}
			
			// Dynamically load jQuery
			function loadJQuery(callback) {
				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function(data) {
					if (xhr.readyState == 4) {
						if (xhr.status == 200) {
							callback(xhr.responseText);
						} else {
							callback(null);
						}
					}
				}
				var url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
				xhr.open('GET', url, true);
				xhr.send();
			};

			function onRequest(request, sender, callback) {
				switch(request.action) {
					case 'loadJQuery':
						loadJQuery(callback);
						break;
					case 'showPageAction':
						showPageAction(sender.tab);
						callback();
						break;
					case 'addUrlToHistory':
						chrome.history.addUrl({url: request.url});
						break;
					case 'getOptions':
						callback(options);
						break;
					case 'optionsChanged':
						options = request.options;
						break;				
				}
			};
			
			function showPageAction(tab) {
				if (options.extensionEnabled) {
					chrome.pageAction.setIcon({tabId: tab.id, path: 'images/icon19.png'});
					chrome.pageAction.setTitle({tabId: tab.id, title: 'Hover Zoom\nClick to disable automatic image zooming'});
				} else {
					chrome.pageAction.setIcon({tabId: tab.id, path: 'images/icon19d.png'});
					chrome.pageAction.setTitle({tabId: tab.id, title: 'Hover Zoom\nClick to enable automatic image zooming'});
				}
				chrome.pageAction.show(tab.id);
			}
			
			function pageActionOnClick(tab) {
				// Store new state
				options.extensionEnabled = !options.extensionEnabled;
				localStorage.options = JSON.stringify(options);
				
				sendOptions(options);
			}
			
			function init() {				
				// Load options
				options = loadOptions();
						
				// Bind events
				chrome.extension.onRequest.addListener(onRequest);				
				chrome.pageAction.onClicked.addListener(pageActionOnClick);
			}

			init();
		</script>
	</body>
</html>